﻿using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace KXmlUIControl
{
    public class XmlButtonObject : XmlControlBase
    {
        public string Image { get; set; }

        public string Click { get; set; }

        public XmlButtonObject()
            : base()
        {

        }

        public void SetImage(Button btn)
        {
            if (string.IsNullOrEmpty(Image))
            {
                return;
            }
            System.Drawing.Image image = StaticTypes.GetButtonImage(Image);
            if (image == null)
            {
                image = StaticTypes.GetIconImage(Image);
            }
            if (btn != null)
            {
                btn.Image = image;
                btn.ImageAlign = ContentAlignment.MiddleCenter;
            }
        }

        public override string ToXMLString()
        {
            throw new NotImplementedException();
        }

        private void AddEventClick(Button btn, object parent)
        {
            BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
            if (!string.IsNullOrEmpty(Click))
            {
                Type t = parent.GetType();
                System.Reflection.MethodInfo methodInfo = t.GetMethod(Click, flag);
                if (methodInfo != null)
                {
                    Delegate DelegateInstance = StaticTypes.CreateDelegateFromMethodInfoByDelegate<EventHandler>(parent, methodInfo);
                    if (DelegateInstance != null)
                    {
                        EventHandler handler = DelegateInstance as EventHandler;
                        btn.Click += handler;
                    }
                }
            }
        }

        public override Control ToControl(object parent)
        {
            Button btn = new Button();
            SetValues(btn);
            SetImage(btn);
            AddEventClick(btn, parent);
            return btn;
        }
    }
}
